/**
 * Created by Jie on 2017/2/6.
 */
var async = require('async');
var Model = require('../../model/core/role');



var index = {page:'core/role',title:''};
var form = {page:'core/_form/_role_form',title:'角色信息管理'};

exports.index = function (req,res) {
    res.render(index.page, {title: index.title});
};

exports.form = function (req,res) {
    var model = new Model();
    model.one(req.params.id,function (err,result) {
        if(result.error == 1){
            res.render(form.page, {title: form.title});
        }else{
            res.render(form.page, {title: form.title,obj:result.data});
        }
    })
};

exports.one = function (req,res) {
    var model = new Model();
    model.one(req.params.id,function (err,result) {
        res.json(result);
    })
}

exports.insert = function (req,res) {
    var model = new Model();
    var json = req.body;
    var where = " and name='"+json.name+"' ";
    async.waterfall([
        function(callback) {
            model.checkName(where,function (err,result) {
                callback(null,result);
            });
        },
        function(check, callback) {
            if(check.error == 1){
                callback(null,check);
            }else {
                model.insert(req.body,function (err,result) {
                    callback(null,result);
                });
            }
        }
    ], function(error, result) {
        res.json(result);
    });
}

exports.edit = function (req,res) {
    var model = new Model();
    var json = req.body;
    var id = req.params.id;
    var where = " and name='"+json.name+"' and id<>"+id+" ";
    req.body.id = id;
    async.waterfall([
        function(callback) {
            model.checkName(where,function (err,result) {
                callback(null,result);
            });
        },
        function(check, callback) {
            if(check.error == 1){
                callback(null,check);
            }else {
                model.edit(req.body,function (err,result) {
                    callback(null,result);
                });
            }
        }
    ], function(error, result) {
        res.json(result);
    });
}

exports.del = function (req,res) {
    var model = new Model();
    req.body.id = req.params.id;
    model.del(req.body,function (err,result) {
        res.json(result);
    });
}

exports.list = function (req,res) {
    var model = new Model();
    var where = req.body;
    model.list(where,function (err,result) {
        res.json(result);
    });
}

exports.all = function (req,res) {
    var model = new Model();
    var cond = {where:'',order:''};
    model.all(cond,function (err,result) {
        res.json(result);
    });
}